package com.tl.bootmeter.config;

import com.tl.bootmeter.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class doFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpSession session = req.getSession();
        User user = (User)session.getAttribute("user");
        System.out.println("过滤器--------------"+user);
        //如果session中的用户为空，那么判定为未登陆
        if(user == null){
            String uri = req.getRequestURI();
            if(uri.equals("/BootMeter/")
                    || uri.indexOf("/") != -1
            ){
                filterChain.doFilter(servletRequest, servletResponse);
                System.out.println("过滤器,html页面判定------>"+uri.indexOf(".html"));
            }else if(uri.indexOf(".html") != -1){
                req.setAttribute("message", "请登录后进行访问！");
                req.getRequestDispatcher("/login.html").forward(servletRequest, servletResponse);
            }else if(uri.equals("/BootMeter/")
                    //对静态资源进行放行
                    || uri.indexOf(".do") != -1
                    || uri.indexOf(".css") != -1
                    || uri.indexOf(".js") != -1
                    || uri.indexOf(".png") != -1
                    || uri.indexOf(".jpg") != -1
            ){
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
